package com.platform.modules.phone.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.common.utils.HttpUtils;
import com.platform.common.utils.XmlUtils;
import com.platform.modules.mall.entity.MallPhoneTopUpLogEntity;
import com.platform.modules.mall.service.MallPhoneTopUpLogService;
import com.platform.modules.phone.PhoneTopUpContants;
import com.platform.modules.phone.config.PhoneSelInfoConfig;
import com.platform.modules.phone.config.PhoneTopUpConfig;
import com.platform.modules.phone.entity.PhoneSelInfoReqEntity;
import com.platform.modules.phone.entity.PhoneSelInfoResEntity;
import com.platform.modules.phone.entity.PhoneTopUpReqEntity;
import com.platform.modules.phone.entity.PhoneTopUpResEntity;
import com.platform.modules.phone.entity.dto.PhoneTopUpCallBackDto;
import com.platform.modules.phone.entity.dto.PhoneTopUpDto;
import com.platform.modules.phone.service.PhoneTopUpService;
import com.platform.modules.phone.utils.PhoneTopUpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class PhoneTopUpServiceImpl implements PhoneTopUpService {
    @Resource(name = "phoneTopupConfig")
    PhoneTopUpConfig topUpConfig;

    @Resource(name = "phoneSelInfoConfig")
    PhoneSelInfoConfig selInfoConfig;

    @Resource
    private MallPhoneTopUpLogService logService;

    private static final SimpleDateFormat sdf = new SimpleDateFormat(PhoneTopUpContants.DATE_PATTERN);

    @Override
    public void topUp(PhoneTopUpDto dto) {
        // 初始化日志
        MallPhoneTopUpLogEntity entity = new MallPhoneTopUpLogEntity();
        entity.setOrderId(dto.getOrderId());
        entity.setUserId(dto.getUserId());
        entity.setCreateTime(new Date());
        try {
            // 构建 请求数据
            PhoneTopUpReqEntity reqEntity = new PhoneTopUpReqEntity(topUpConfig);
            // 订单价格以元为单位  第三方以分为单位
            BigDecimal topupMoney = dto.getTopUpMoney().multiply(BigDecimal.valueOf(100L));
            reqEntity.setDatetime(sdf.format(new Date()));
            reqEntity.setOrderID(dto.getOrderId());
            reqEntity.setValue(topupMoney.toBigInteger());
            reqEntity.setChargeNo(dto.getCartNo());

            // 按照第三方的格式  进行数据处理
            String orderInfo = PhoneTopUpUtils.buildRequestInfo(reqEntity);
            String sign = PhoneTopUpUtils.sign(orderInfo, topUpConfig.getKey());

            // http 请求的参数列表
            Map<String, String> params = new HashMap<>();
            params.put(PhoneTopUpContants.REQ_DATA_K, orderInfo);
            params.put(PhoneTopUpContants.REQ_SIGN_K, sign);
            log.info("--------------------话费充值--请求参数Orderinfo:{}", orderInfo);
            log.info("--------------------话费充值--请求参数Sign:{}", sign);

            // 调用请求
            String respXml = HttpUtils.sendPostForm(topUpConfig.getRequestUrl(), params, PhoneTopUpContants.REQ_CHARSET, PhoneTopUpContants.RES_CHARSET);
            log.info("--------------------话费充值--响应结果:\n{}", respXml);

            // 解析xml 响应
            PhoneTopUpResEntity res = XmlUtils.parseXml(PhoneTopUpResEntity.class, respXml);

            // 调用完成后 记录数据
            entity.setRespons(respXml);
            entity.setError_msg(res.getTranInfo());
            entity.setStatus(res.getTranStat().equals(1) ? 0 : -1);
        } catch (Exception e) {
            entity.setStatus(-1);
            e.printStackTrace();
        }
        logService.save(entity);
    }

    @Override
    public void selTopUpInfo(String orderId) throws Exception {
        // 构建请求数据
        PhoneSelInfoReqEntity reqEntity = new PhoneSelInfoReqEntity(selInfoConfig);
        reqEntity.setOrderID(orderId);

        // 处理参数
        String orderInfo = PhoneTopUpUtils.buildRequestInfo(reqEntity);
        String sign = PhoneTopUpUtils.sign(orderInfo, selInfoConfig.getKey());
        Map<String, String> params = new HashMap<>();
        params.put(PhoneTopUpContants.REQ_DATA_K, orderInfo);
        params.put(PhoneTopUpContants.REQ_SIGN_K, sign);
        log.info("--------------------查询话费充值订单--请求参数Orderinfo:{}", orderInfo);
        log.info("--------------------查询话费充值订单--请求参数Sign:{}", sign);

        // 调用请求并解析
        String respXml = HttpUtils.sendPostForm(selInfoConfig.getRequestUrl(), params, PhoneTopUpContants.REQ_CHARSET, PhoneTopUpContants.RES_CHARSET);
        log.info("--------------------查询话费充值订单--响应结果:\n{}", respXml);
        PhoneSelInfoResEntity res = XmlUtils.parseXml(PhoneSelInfoResEntity.class, respXml);
        System.out.println("resp:" + res);
    }

    @Override
    public void topupCallBack(PhoneTopUpCallBackDto dto) {
        String orderId = dto.getOrderID();
        // 查询对应日志记录
        QueryWrapper<MallPhoneTopUpLogEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);
        queryWrapper.eq("status", 0);
        MallPhoneTopUpLogEntity logEntity = logService.getOne(queryWrapper);
        // 修改信息
        if (logEntity != null) {
            MallPhoneTopUpLogEntity updateEntity = new MallPhoneTopUpLogEntity();
            updateEntity.setId(logEntity.getId());
            updateEntity.setUpdateTime(new Date());
            if (dto.getTranStat().equals(1)) {
                updateEntity.setStatus(1);
            } else {
                // todo 充值失败， 后续重新充值
                updateEntity.setStatus(2);
            }
            logService.updateById(updateEntity);
            return;
        }
    }


}
